#include "qmsgbrowser.h"

QMsgBrowser::QMsgBrowser(QWidget *parent)
    : QTextBrowser(parent)
{
    m_listEmotionUrl.clear();
    m_emotionMap.clear();
}

QMsgBrowser::~QMsgBrowser()
{
    delteAllEmotionImage();
}

void QMsgBrowser::delteAllEmotionImage()
{
    for (auto itor = m_emotionMap.constBegin(); itor != m_emotionMap.constEnd(); ++itor)
    {
        delete itor.key();
    }
    m_emotionMap.clear();
}
QString QMsgBrowser::giftoHtml(QString content)
{
    QString nStr=content;
                QRegExp imgTagRegex("\\<img[^\\>]*src\\s*=\\s*\"([^\"]*)\"[^\\>]*\\>", Qt::CaseInsensitive);
                imgTagRegex.setMinimal(true);
                QStringList imgSrcList;
                QStringList imgTagList;
                int offset = 0;
                while( (offset = imgTagRegex.indexIn(content, offset)) != -1){
                    offset += imgTagRegex.matchedLength();
                    imgTagList.append(imgTagRegex.cap(0));
                    imgSrcList.append(imgTagRegex.cap(1));
                    QString tmpstr=addEmotionUrl(imgTagRegex.cap(1));
                    nStr=nStr.replace(imgTagRegex.cap(0),tmpstr);
                }
                return nStr;

}
QString QMsgBrowser::addEmotionUrl(QString imageName)
{

    const QString&& flagName = QString("apng-%1-apng").arg(imageName);
    QString insertHtml=QString("<img src='%1'/>").arg(flagName);
    if (m_listEmotionUrl.contains(imageName))
        return "";
    else
        m_listEmotionUrl.append(imageName);

    QMovie* apngMovie = new QMovie(imageName, "apng", this);
    apngMovie->setCacheMode(QMovie::CacheNone);
    m_emotionMap.insert(apngMovie, flagName);

    connect(apngMovie, SIGNAL(frameChanged(int)), this, SLOT(onEmotionImageFrameChange(int)));
    apngMovie->start();
    return insertHtml;
}

void QMsgBrowser::onEmotionImageFrameChange(int frame)
{
    QMovie* movie = qobject_cast<QMovie*>(sender());
    document()->addResource(QTextDocument::ImageResource, QUrl(m_emotionMap.value(movie)), movie->currentPixmap());
    setLineWrapColumnOrWidth(lineWrapColumnOrWidth());
}


